﻿/**

	
	Uses getURL for most browsers, fscommand for ie.
	Will parse out the javascript: scheme if it is sent in the function name.
	

	@author Chandler McWilliams
	@version 2005-11-17
	
	@usage
	<code>
	timber.browser.call('myFunction', 'myargs');
	</code>
	or
	<code>
	timber.browser.call('javascript:myFunction("myargs")');
	</code>

	@notes
	Remember to hande the js event you need to add this to the html:
	<code>
		<script type="text/vbscript">
		<!--  <![CDATA[
		Sub MOVIEHTMLID_FSCommand(ByVal command, ByVal args)
		 call eval(command)(args)
		end sub
		// ]]>
		-->
		</script>
	</code>
	where MOVIEHTMLID is the id of the movie in the html.

*/



 
class timber.browser.JS
{
	public static function call(funcName, args) {
		
		// if the funcname begins with javascript: then this is a url style call
		// and needs to be formatted
		if(funcName.indexOf('javascript:') == 0) {
			var obj = JS.parseJavaScript(funcName);
			funcName = obj.func;
			arguments = obj.args;
		} else {
			arguments.shift();
		}

		if (System.capabilities.playerType == "ActiveX") {
			args = arguments.toString();
			fscommand( funcName , args );
			
		} else {
			// make sure to escape all '
			for (var i=0; i<arguments.length; i++) {
				if (arguments[i].indexOf("'") > -1) {
					arguments[i] = arguments[i].split("'").join("\\'");
				}	
			}
			
			args = "'" + arguments.join("','") + "'";
			var jsurl = "javascript:"+funcName+"("+ args +");";			

			if ( _url.indexOf("http") != -1 ) {				// make sure we are not local
				getURL(jsurl);
			} else {
				trace('JS call intercepted becuase page is local. Remember that viewing files via file:// will fail too.');
				trace(jsurl);
			}
		}
	}
	
	/**
		Turn a javascript scheme string. ie: javascript:alert('boo');
		Into something we can call.
		
		@param src string
		@return object with 2 properties, the function and the args
	**/
	public static function parseJavaScript(src) {
		var parts = src.substring(11);
		var popen = parts.indexOf('(');
		var pclose = parts.lastIndexOf(')');
		var func = parts.substring(0, popen);
		var args = parts.substring(popen+1, pclose).split(',');

		// trim the args
		var trim = function(str) {
			var i = 0;	
			while(str.charCodeAt(i) == 32 
				|| str.charCodeAt(i) == 13 
				|| str.charCodeAt(i) == 10 
				|| str.charCodeAt(i) == 9) {
				i++;
			}	
			return str.substring(i,str.length);
		} 
		
		// kill the " and ' in args
		var c;
		for (var i=0; i<args.length; i++) {
			args[i] = trim(args[i]);
			c = args[i].charAt(0);
			if ((c == '"') || (c == "'")) {
				args[i] = args[i].substring(1, args[i].lastIndexOf(c));
			}
		}		
		return {func: func, args: args};
	}
}